#include "common.h"
#include "ImServiceCommon_types.h"

#include <boost/lexical_cast.hpp>

#include "im/adapters/user_profile_adapter.h"

namespace imserver {

const char * IM_QID_COOKIE = "qimrid";
const char * IM_QID_TICKET_COOKIE = "qimrk";

const char * IM_TEMP_ID_COOKIE = "qimtid";
const char * IM_TEMP_ID_TICKET_COOKIE = "qimtk";

const int64_t IM_TEMP_ID_BASE = 10000000000000;

char * kDefaultHeadPic = "http://imstatic.bang.360.cn/imdefault.jpg";

const int MSG_TYPE_TALK           = 0;
const int MSG_TYPE_LOGIN_NOTIFY   = 1;
const int MSG_TYPE_OFFLINE_NOTIFY = 2;
const int MSG_TYPE_PRESENCE       = 3;
const int MSG_TYPE_TYPING         = 4;
const int MSG_TYPE_BANG_ORDER     = 5;

const char * MessageTypeName(int type) {
  switch(type) {
  case MSG_TYPE_TALK:
    return "MSG_TYPE_TALK";
  case MSG_TYPE_LOGIN_NOTIFY:
    return "MSG_TYPE_LOGIN_NOTIFY";
  case MSG_TYPE_OFFLINE_NOTIFY:
    return "MSG_TYPE_OFFLINE_NOTIFY";
  case MSG_TYPE_PRESENCE:
    return "MSG_TYPE_PRESENCE";
  case MSG_TYPE_TYPING:
    return "MSG_TYPE_TYPING";
  default:
    return "MSG_TYPE_UNKNOWN";
  }
}

const char * SessionTypeName(int type) {
  switch(type) {
  case SessionType::OFFLINE:
    return "OFFLINE";
  case SessionType::WEB:
    return "WEB";
  case SessionType::CLIENT:
    return "CLIENT";
  case SessionType::HIDDEN:
    return "HIDDEN";
  default:
    return "UNKNOWN_SESSION_TYPE";
  }
}

int MessageType(const ImMessage & message) {
  return (message.flags & 0xFF00) >> 8;
}
void SetMessageType(ImMessage & message, int type) {
  message.flags = message.flags | 0xFF00 & (type << 8);
}

int GetSessionShardId(const std::string & session) {
  size_t pos = session.find_last_of('_');
  if (pos == std::string::npos) {
    return -1;
  }
  try {
    return boost::lexical_cast<int64_t>(session.substr(pos + 1));
  } catch (boost::bad_lexical_cast&) {
    return -2;
  }
}

std::string GetUsername(int64_t qid) {
  UserProfile user;
  int res = UserProfileAdapter::Instance().Get(qid, &user, 2);
  if (res != 0 || user.username.empty()) {
    return GetDefaultUsername(qid);
  }

  return user.username;
}

std::string GetDefaultUsername(int64_t uid) {
  std::stringstream ss;
  if (uid < IM_TEMP_ID_BASE) {
    ss << uid;
  } else {
    ss << "访客" << (uid % IM_TEMP_ID_BASE);
  }
  return ss.str();
}

}

